package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserSoundApi;
import com.tanhua.dubbo.api.UserSoundTimeApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.SoundType;
import com.tanhua.model.mongo.UserSound;
import com.tanhua.model.mongo.UserSoundTime;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserSoundVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @Description: test
 * @Create by: 熊孩子
 * @Date: 2021/12/11 11:39
 */
@Service
public class PeachblossomService {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @DubboReference
    private UserSoundApi userSoundApi;

    @DubboReference
    private UserSoundTimeApi userSoundTimeApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private TanhuaService tanhuaService;

    //发送语音
    public void sendPeachblossom(MultipartFile soundFile) throws IOException {
        //判断文件是否为空
        if (soundFile.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }
        //调用api查询发送语音剩余次数
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        UserSoundTime userSoundTime = userSoundTimeApi.queryUserSoundTime(UserHolder.getUserId(), date, SoundType.SEND);

        if (userSoundTime != null && userSoundTime.getResidueCount() < 1) {
            throw new BusinessException(ErrorResult.builder().errMessage("今日发送语音次数已用完，请明日再来！").build());
        }
        //保存用户语音并保存/修改发送次数
        //1.将语音上传到FastDFS,获取访问URL
        String filename = soundFile.getOriginalFilename();//文件名a.MP3
        filename = filename.substring(filename.lastIndexOf(".") + 1);//后缀名
        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), filename, null);
        String soundFileUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        //2、构建userSound对象
        UserSound userSound = new UserSound();
        userSound.setUserId(UserHolder.getUserId());
        userSound.setCreated(System.currentTimeMillis());
        userSound.setDate(date);
        userSound.setSoundFileUrl(soundFileUrl);
        //调用API保存语音数据，并保存/修改发送次数
        userSoundApi.save(userSound);
    }

    //接收语音
    public UserSoundVo receivePeachblossom() {

        //调用api查询接收语音剩余次数
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        UserSoundTime userSoundTime = userSoundTimeApi.queryUserSoundTime(UserHolder.getUserId(), date, SoundType.RECEIVE);

        if (userSoundTime != null && userSoundTime.getRemainingTimes() < 1) {
            throw new BusinessException(ErrorResult.builder().errMessage("今日接收语音次数已用完，请明日再来！").build());
        }

        UserSoundVo vo = new UserSoundVo();//返回值

        if (userSoundTime == null) {
            //还未接收过，当日第一次接收，从usersoud随机接收一条语音排除自己的语音
            UserSound userSound = userSoundApi.randomSound(UserHolder.getUserId());
            if (userSound != null) {
                //保存当前用户的语音接收次数
                userSoundTime = new UserSoundTime();
                userSoundTime.setUserId(UserHolder.getUserId());
                userSoundTime.setSoundType(SoundType.RECEIVE.getType());
                userSoundTime.setDate(date);
                userSoundTime.setRemainingTimes(9);
                userSoundTimeApi.save(userSoundTime);
                //查询随机用户的信息
                UserInfo userInfo = userInfoApi.findById(userSound.getUserId());
                //构造vo
                vo = UserSoundVo.init(userInfo, userSound, userSoundTime);
            }
            //获取之后，删除语音
            userSoundApi.delete(userSound.getId());

        } else {  //userSoundTime不为null且剩余接收次数大于1
            //从usersoud随机接收一条语音排除自己的语音
            UserSound userSound = userSoundApi.randomSound(UserHolder.getUserId());
            if (userSound != null) {
                //修改当前用户的语音接收次数
                userSoundTimeApi.update(userSoundTime);
                //查询随机用户的信息
                UserInfo userInfo = userInfoApi.findById(userSound.getUserId());
                //构造vo
                vo = UserSoundVo.init(userInfo, userSound, userSoundTime);
            }
            //获取之后，删除语音
            userSoundApi.delete(userSound.getId());
        }
        //构造返回值
        return vo;
    }


}
